package com.renwei.yunlong.activity.news;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.event.ChatCloseEvent;
import com.renwei.yunlong.event.ChatDeleteEvent;
import com.renwei.yunlong.event.ChatNameRefreshEvent;
import com.renwei.yunlong.event.ChatNotGroupEvent;
import com.renwei.yunlong.event.MessageRefreshEvent;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.model.CSCustomServiceInfo;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * Created by wangqi on 2018/1/3.
 */

public class ConversationActivity extends BaseActivity {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    private String mTargetId;
    private Conversation.ConversationType mConversationType;
    private String outSourceFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        showInput = false;

        initView();
    }

    private void initView() {
        Intent intent = getIntent();

        if (intent == null || intent.getData() == null)
            return;

        mTargetId = intent.getData().getQueryParameter("targetId");
        //10000 为 Demo Server 加好友的 id，若 targetId 为 10000，则为加好友消息，默认跳转到 NewFriendListActivity
        // Demo 逻辑
        if (mTargetId != null && mTargetId.equals("10000")) {
//            startActivity(new Intent(ConversationActivity.this, NewFriendListActivity.class));
            return;
        }
        mConversationType = Conversation.ConversationType.valueOf(intent.getData()
                .getLastPathSegment().toUpperCase(Locale.US));


        String title = intent.getData().getQueryParameter("title");
        simpleTileView.setTitle(title);

        // 保存对方信息
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String url = bundle.getString("url");
            CSCustomServiceInfo csInfo = bundle.getParcelable("customServiceInfo");
            if (url != null && url.length() > 0) {
                RongUserInfoManager.getInstance().setUserInfo(new UserInfo(mTargetId, title, Uri.parse(url)));
            } else if (csInfo != null) {
                //    RongUserInfoManager.getInstance().set(new UserInfo(mTargetId, title, Uri.parse(url)));
            }
        }
        // 设置右上角的功能
        if (mConversationType == Conversation.ConversationType.PRIVATE) {
            // 模拟发送一条公告
//            NoticeMessage noticeMessage = new NoticeMessage("标题标题标题标题标题标题",
//                    "内容内容内容内容内","","");
//            Message message = Message.obtain(mTargetId, Conversation.ConversationType.PRIVATE, noticeMessage);
//            RongIM.getInstance().sendMessage(message, "公告", null, new IRongCallback.ISendMediaMessageCallback() {
//                @Override
//                public void onProgress(Message message, int i) {
//
//                }
//
//                @Override
//                public void onCanceled(Message message) {
//
//                }
//
//                @Override
//                public void onAttached(Message message) {
//
//                }
//
//                @Override
//                public void onSuccess(Message message) {
//                    LogUtil.e("公告消息发送成功");
//                }
//
//                @Override
//                public void onError(Message message, RongIMClient.ErrorCode errorCode) {
//
//                }
//            });


            simpleTileView.setRightOption(R.mipmap.icon_chat_single, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if ("1".equals(mTargetId)) {
                        CustomServiceInfoActivity.OpenActivity(ConversationActivity.this);
                    } else {
                        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
                        String url = userInfo.getPortraitUri().toString();
                        String outSourceFlag = "";
                        if (!TextUtils.isEmpty(url) && url.contains("CloudServer")) {
                            //业主
                            if ("1".equals(companyType)) {
                                outSourceFlag = "0";
                            } else {
                                outSourceFlag = "1";
                            }
                        } else {
                            // 服务商
                            if ("1".equals(companyType)) {
                                outSourceFlag = "1";
                            } else {
                                outSourceFlag = "0";
                            }
                        }
                        ChatSettingActivity.OpenActivity(ConversationActivity.this, mConversationType,
                                mTargetId, outSourceFlag);
                    }
                }
            });
        } else if (mConversationType == Conversation.ConversationType.GROUP) {
            simpleTileView.setRightOption(R.mipmap.icon_chat_group, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ChatSettingActivity.OpenActivity(ConversationActivity.this, mConversationType,
                            mTargetId, "");
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onDeleteEvent(ChatDeleteEvent event) {
        RongIM.getInstance().removeConversation(mConversationType, mTargetId);
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onCloseEvent(ChatCloseEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onNameRefreshEvent(ChatNameRefreshEvent event) {
        simpleTileView.setTitle(event.name);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onNameRefreshEvent(ChatNotGroupEvent event) {
        DialogUtils.showSingleDialog(mContext, "您已不在群组", false, new DialogUtils.OnDialogClickListener() {
            @Override
            public void onCancel(Dialog dialog) {
            }

            @Override
            public void onConfirm(Dialog dialog) {
                dialog.dismiss();
                RongIM.getInstance().removeConversation(mConversationType, mTargetId);
                finish();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new MessageRefreshEvent(false));
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }
}